import ErrorCode from "../script/ErrorCode";
import { Toast } from "vant";
import { saveToLocal, loginToNative } from "../script/fn";
export const fastLogin = {
  created() {},
  methods: {
    //清空表单
    empty() {
      this.send.phoneNumber = "";
      this.send.phoneAuthCode = "";
    },
    //根据内容判断禁用登录按钮
    disable() {
      const valid_phone = this.$validate.phone.regex.test(
        this.send.phoneNumber
      );
      const valid_AuthCode = this.$validate.notEmpty.regex.test(
        this.send.phoneAuthCode
      );
      if (this.show == 0) {
        if (valid_phone && valid_AuthCode) {
          this.$emit("toggHeight", true);
        } else {
          this.$emit("toggHeight", false);
        }
      }
    },
    //格式化数据
    formatData(arr) {
      let zbInfos = [];
      arr.map(item => {
        let zbInfo = {};
        zbInfo["zbId"] = item.targetId || "";
        zbInfo["zbKey"] = item.clientTarget.keywords || "";
        zbInfo["zbName"] = item.clientTarget.targetName || "";
        zbInfo["zbExpireFlag"] = item.clientTarget.targetModel || 0;
        zbInfo["zbCreateTime"] = String(item.createTime) || "";
        zbInfo["zbEndTime"] = String(item.endTime) || "";
        zbInfo["zbIsExpire"] = item.isEnd || 0;
        zbInfo["zbAvailableTimes"] = item.clientTarget.stockNum || 0;
        zbInfo["zbUsedTimes"] = item.clientTarget.useStockNum || 0;
        zbInfo["stock"] = [];
        if (
          item.clientTarget.targetRecords != undefined &&
          item.clientTarget.targetRecords.length > 0
        ) {
          item.clientTarget.targetRecords.map(i => {
            let stocks = {};
            stocks["code"] = Number(i.code) || 0;
            stocks["stockCode"] = i.stockCode || "";
            zbInfo["stock"].push(stocks);
          });
        }
        zbInfos.push(zbInfo);
      });
      return zbInfos;
    },
    //登录
    submit() {
      const self = this;
      if (!this.$validate.notEmpty.regex.test(this.send.phoneNumber)) {
        return this.$emit("showError", this.$validate.notEmpty.error);
      }
      if (!this.$validate.phone.regex.test(this.send.phoneNumber)) {
        return this.$emit("showError", this.$validate.phone.error);
      }
      if (!this.$validate.notEmpty.regex.test(this.send.phoneAuthCode)) {
        return this.$emit("showError", this.$validate.notEmpty.error);
      }
      if (!navigator.onLine) return Toast("网络连接失败，请检查网络设置");
      const { version } = this.$fn.getUrlParams();
      this.$store
        .dispatch("phoneAuthcodeLogin", {
          phoneNumber: this.send.phoneNumber,
          phoneAuthCode: this.send.phoneAuthCode,
          loginVersion: !version || version == 1 ? 2 : version
        })
        .then(function({ data, status }) {
          self.$emit("goBuy", false);
          if (status != 1) {
            if (status == 400001) {
              self.$emit("goBuy", true);
            } else {
              self.$emit("showError", ErrorCode[status]);
            }
          } else {
            if (version >= 3) {
              saveToLocal(
                {
                  productId: data.order.productId,
                  userId: data.userId,
                  endTime: data.order.endTime
                } //订单结束时间
              );
            }
            saveToLocal({ phoneNumber: self.send.phoneNumber });
            self.$store.dispatch("findUserTarget").then(back => {
              if (!back) {
                window.prompt(
                  "",
                  `up://["web_user_login",${Date.now()},{"type":"login","data":{"token":"${
                    window.userInfo.centralToken
                  }","time":"${window.systemTime}","logintype":"0","openid":"${
                    window.userInfo.phone
                  }","indexcollection":0,"expiretime":"${
                    data.order ? data.order.endTime : ""
                  }","productid":"${
                    data.order ? data.order.productId : ""
                  }","isInside":${window.userInfo.isInside},"zbInfo":[]}}]`
                );
              } else {
                window.prompt(
                  "",
                  `up://["web_user_login",${Date.now()},{"type":"login","data":{"token":"${
                    window.userInfo.centralToken
                  }","time":"${window.systemTime}","logintype":"0","openid":"${
                    window.userInfo.phone
                  }","indexcollection":1,"expiretime":"${
                    data.order ? data.order.endTime : ""
                  }","productid":"${
                    data.order ? data.order.productId : ""
                  }","isInside":${
                    window.userInfo.isInside
                  },"zbInfo":${JSON.stringify(self.formatData(back))}}}]`
                );
              }
            });
          }
        });
    },
    //显示图片验证码组件
    getAuthCode() {
      if (this.authStatus == 1) return;

      if (!this.$validate.phone.regex.test(this.send.phoneNumber)) {
        return this.$emit("showError", this.$validate.phone.error);
      }
      this.$emit("getAuthCode");
    },
    getPhoneCode(authCode) {
      const self = this;
      if (!navigator.onLine) return Toast("网络连接失败，请检查网络设置");
      this.$store
        .dispatch("sendPhoneAuthcode", {
          phoneNumber: this.send.phoneNumber,
          imageAuthcode: authCode
        })
        .then(function(data) {
          if (data.status != 1) {
            return self.$emit("showError", ErrorCode[data.status]);
          }
          self.countDown();
        });
    },
    countDown() {
      const TIME_COUNT = 59,
        self = this;
      let timer;
      if (!timer) {
        let second = TIME_COUNT;
        this.authStatus = 1;
        self.count = "60s重新获取";
        timer = setInterval(() => {
          if (second > 0 && second <= TIME_COUNT) {
            self.count = second-- + "s重新获取";
          } else {
            clearInterval(timer);
            timer = null;
            self.authStatus = 0;
          }
        }, 1000);
      }
    }
  }
};
